package com.ruipengkj.view.statementView;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.TableColumnModel;

import com.ruipengkj.bean.TRight;
import com.ruipengkj.bean.TRole;
import com.ruipengkj.bean.TRoleRight;
import com.ruipengkj.commons.BuildSpringApplication;
import com.ruipengkj.model.MemberQueryRightModel;
import com.ruipengkj.service.TRightService;
import com.ruipengkj.service.TRoleRightIMService;
import com.ruipengkj.service.TRoleRightService;
import com.ruipengkj.view.base.BasePanel;
//集成分页组件
public class StatementPermissions extends BasePanel implements Runnable{
		private static final long serialVersionUID = 1L;
		//private JLabelJTextFieldComponent cardNumTF = null;//发卡时间
		
		
		private JButton queryButton = null;//添加权限
		private String JRoleID= null;
		
		private JTable table;
		private MemberQueryRightModel memberQueryRightModel;
		//private PagingComponent pagingComponent;//翻页组件
		//private PageView<TRight> pageView;//翻页主键
		private JScrollPane tableJsp;
		private TRightService tRightService;
		private TRoleRightService tRoleRightService;
		private TRoleRightIMService tRoleRightIMService;
		private JPanel onePanel = uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
		private JPanel []jp;
		private JPanel []jp1;
		private JCheckBox []jCheckBox;
		//private MemberCashCardDetail memberDetailDialog;//会员详细窗体
		public StatementPermissions() {
			tRightService=BuildSpringApplication.getInstance().getTRightServiceImpl();
			tRoleRightService = BuildSpringApplication.getInstance().getTRoleRightServiceImpl();
			tRoleRightIMService = BuildSpringApplication.getInstance().getTRoleRightIMServiceImpl();
			this.setLayout(new BorderLayout());
			this.initViews();
			this.init();
			this.initListener();
//			ApplicationContext.CardUtilThread.setFlag(false);//停止之前线程
//			ApplicationContext.CardUtilThread=new CardUtil(){//重新定义线程
//				protected void send(String drive){
//					cardNumTF.getText().setText(drive);
//					cardNumTF.requestFocus();
//				}
//			};
//			ApplicationContext.CardUtilThread.startOn(cardNumTF.getText());//启动线程
		}
		private void initListener() {
			// TODO Auto-generated method stub
			//queryButton.addActionListener(this);
		}
		private void initViews() {
			List<TRight> listRight = new ArrayList<TRight>();
			
			try {
				boolean isCount=false;
				int count=0;
				listRight = tRightService.getScrollService(null);
				Collections.sort(listRight, new Comparator<TRight>()
						{
							@Override
							public int compare(TRight arg0, TRight arg1) {
								return String.valueOf(arg0.getLevel()).compareTo(String.valueOf(arg1.getLevel()));
							}
							
						});
				 jp=new JPanel[listRight.size()];
				 jp1=new JPanel[listRight.size()];
				 jCheckBox= new JCheckBox[listRight.size()];
				for(int i=0;i<listRight.size();i++){
					if((i+1) < listRight.size()){
						if(listRight.get(i).getLevel() < listRight.get(i+1).getLevel()){
							if(isCount == false){
								isCount=true;
								count = i;
								jp[count]=uiFactory.createFlowJPanel(FlowLayout.LEFT);
								jp1[count] = uiFactory.createBoxJPanel(BoxLayout.Y_AXIS);
								jp1[count].setBorder(BorderFactory.createTitledBorder(listRight.get(count).getName()));
							}else{
								jCheckBox[i] = new JCheckBox(listRight.get(i).getName());
								jCheckBox[i].setBackground(new Color(247, 252, 255));
								jp[count].add(jCheckBox[i]);
							}
														
						}else{ 
							jCheckBox[i] = new JCheckBox(listRight.get(i).getName());
							jCheckBox[i].setBackground(new Color(247, 252, 255));
							jp[count].add(jCheckBox[i]);
							isCount = false;
							jp1[count].add(jp[count]);
							onePanel.add(jp1[count]);
						}
					}else{
						jCheckBox[i] = new JCheckBox(listRight.get(i).getName());
						jCheckBox[i].setBackground(new Color(247, 252, 255));
						jp[count].add(jCheckBox[i]);
						isCount = false;
						jp1[count].add(jp[count]);
						onePanel.add(jp1[count]);
					}
				} 
				this.add(onePanel);
//				this.add(this.topPanel(), BorderLayout.NORTH);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
		private void init() {
			// TODO Auto-generated method stub
			//pageView=new PageView<TRight>();
			memberQueryRightModel=new MemberQueryRightModel();
			table=uiFactory.createRPJTable(memberQueryRightModel, null, this, 30, JLabel.CENTER);
			//table设置列宽度 AUTO_RESIZE_SUBSEQUENT_COLUMNS 填满父容器  JTable.AUTO_RESIZE_OFF 自适应
			table.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
			//tableJsp=new JScrollPane(table);
			tableJsp=uiFactory.createJScrollPane(table);
			//pagingComponent=new PagingComponent();
			//pagingComponent.setPageDelegale(this);
			TableColumnModel columnModel = table.getColumnModel();
			columnModel.getColumn(0).setCellEditor(table.getDefaultEditor(Boolean.class));
			columnModel.getColumn(0).setCellRenderer(table.getDefaultRenderer(Boolean.class));
			this.add(this.topPanel(), BorderLayout.SOUTH);
			this.add(tableJsp, BorderLayout.CENTER);
		}
		private JPanel topPanel() {
			JPanel jp=uiFactory.createFlowJPanel(FlowLayout.LEFT);
			return jp;
		}
		@Override
		public void run() {
			// TODO Auto-generated method stub
			this.termQuery(1);
		}
		
		public void queryRights(String ID)
		{
			JRoleID=ID;
		}
		//条件查询
		protected void termQuery(final int currentPage) {
			final TRight tright=new TRight();
			final TRole trole = new TRole();
			trole.setRoleID(JRoleID);
			new Thread(){
				public void run(){
					try {	
						if(JRoleID!=null && !JRoleID.equals("")){
							List<TRight> pageModel=tRightService.getRoleRightService(trole);
							Collections.sort(pageModel, new Comparator<TRight>()
									{
										@Override
										public int compare(TRight arg0, TRight arg1) {
											return String.valueOf(arg0.getLevel()).compareTo(String.valueOf(arg1.getLevel()));
										}
										
									});
							if(pageModel!=null){
								List<TRoleRight> tRoleRightList = tRoleRightService.selectByRoleID(JRoleID);
								System.out.println(JRoleID);
								List<TRight> listRight = tRightService.getScrollService(null);
								Collections.sort(listRight, new Comparator<TRight>()
										{
											@Override
											public int compare(TRight arg0, TRight arg1) {
												return String.valueOf(arg0.getLevel()).compareTo(String.valueOf(arg1.getLevel()));
											}
											
										});
								memberQueryRightModel.setRowData(pageModel);
								boolean[] bools = memberQueryRightModel.getBools();
								String[] rightType = memberQueryRightModel.getRightType();
								int count=0;
								boolean isCount=false;
								String rightID ;
								for(int i=0;i<listRight.size();i++){
									if(jCheckBox[i] == null)
									{
										continue;
									}
									jCheckBox[i].setSelected(false);
									rightID= listRight.get(i).getRightID();
									 for(int j=0;j<tRoleRightList.size();j++){
										 if(rightID.equals(tRoleRightList.get(j).getTRight().getRightID())){
											 jCheckBox[i].setSelected(true);
											 break;
										 }
									 }
									}								
								SwingUtilities.invokeLater(new Runnable() {
									@Override
									public void run() {
										tableJsp.getViewport().remove(waitComponent);
										tableJsp.getViewport().add(onePanel);
									}
								});
							}else{
								//没有优惠卷信息
								waitComponent.setText("不存在数据");
							}
						}else{
							List<TRight> pageModel=tRightService.getScrollService(tright);
							if(pageModel!=null){
							SwingUtilities.invokeLater(new Runnable() {
									@Override
									public void run() {
										tableJsp.getViewport().remove(waitComponent);
										tableJsp.getViewport().add(onePanel);
//										Util.setJTabelAutoClumnWidth(table);
										//pagingComponent.show();
									}
								});
							}else{
								//没有优惠卷信息
								waitComponent.setText("不存在数据");
							}
						}
						
						
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}.start();
		}
		@Override
		public void actionPerformed(ActionEvent e) {
				Boolean isShow =false;
				List<TRight> tRightList = memberQueryRightModel.getTRightList();
				TRoleRight tRoleRight=new TRoleRight();
				TRole tRole=new TRole();
				tRole.setRoleID(JRoleID);
				tRoleRight.setTRole(tRole);
				
				boolean select = false;//检查是否有选中的商品 如果没选中false 否则true
				for (int i = jCheckBox.length -1 ; i >= 0; --i) {
					if(jCheckBox[i] == null)
					{
						continue;
					}
					if (jCheckBox[i].isSelected()) {
						select = true;
						break;
					}
				}
				if(tRole.getRoleID()==null){
					JOptionPane.showMessageDialog(null, "请先选择用户！");
					return;
				}else if (!select) {
					JOptionPane.showMessageDialog(null, "请先选择权限！");
					return;
				} else {
					try
					{
						tRoleRightIMService.saveRoleRight(JRoleID,tRightList,jCheckBox,tRole);
						JOptionPane.showMessageDialog(null, "操作成功!");
					}
					catch(Exception e1)
					{
						JOptionPane.showMessageDialog(null, "操作失败：" + e1.getMessage());
						e1.printStackTrace();
					}	
					}
				table.updateUI();
			}
		@Override
		public void keyReleased(KeyEvent e) {
			if(e.getKeyCode()==KeyEvent.VK_ENTER){
				
					queryButton.doClick();
				
			}
		}
		/**
		// 鼠标双击 显示详细
		 
		@Override
		public void mouseClicked(MouseEvent e) {
	    	if(e.getSource()==table&&e.getClickCount() == 2){
	    		//表格
	    		String id=table.getValueAt(table.getSelectedRow(), 0).toString();
	    		try {
					TCashCard cashcard=tCashCardService.getByIdService(id);
					if(cashcard==null){
						JOptionPane.showMessageDialog(null, "当前会员不存在");
						return;
					}
					memberDetailDialog=new MemberCashCardDetail(null, "优惠卷详细", true);
					memberDetailDialog.showDialog(cashcard);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
	    	}
	    }
	    */
		@Override
		public void clear() {
			// TODO Auto-generated method stub
			
		}
}
